<template lang="pug">
.view.cp-inv-overview.fix-flex-pos
  //- 查询
  el-form.ov-search(:inline="true")
    el-form-item
      el-select(v-model="keyWordsType", placeholder="请选择", style="width: 80px")
        el-option(label="全部", :value="null")
        el-option(
          v-for="(item, index) in allKeyWordsType",
          :key="index",
          :label="item",
          :value="index")
    el-form-item
      el-input(v-model="keywords", placeholder="名称/品牌/型号/规格/编码/条码/", style="width: 240px")
    el-form-item(label="物料类别 :")
      el-select(v-model="skuType", placeholder="请选择", style="width: 116px")
        el-option(label="全部", :value="null")
        el-option(
          v-for="item in skuTypeSelect",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item(label="物料分级 :")
      el-select(v-model="grade", placeholder="请选择", style="width: 116px")
        el-option(label="全部", :value="null")
        el-option(
          v-for="item in skuLevelSelect",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item(label="仓库 :")
      el-select(v-model="viewStore", placeholder="请选择", style="width: 116px")
        el-option(label="全部", :value="null")
        el-option(
          v-for="item in allStorehouse",
          :key="item.value",
          :label="item.name",
          :value="item.value")
    el-form-item
      el-button(type="primary", @click="search", style="width: 116px") 搜索
    el-form-item
      el-button(plain, @click="exportReport", style="width: 116px") 导出
  //- 表格
  .ov-table
    el-table(
      :data="inventoryViews",
      highlight-current-row,
      v-loading="loadingOverview",
      size="mini",
      height="100%")
      el-table-column(show-overflow-tooltip, type="index", :index="indexMethod", label="序号")
      el-table-column(label="物料编码")
        template(slot-scope="scope")
          el-tooltip(
            effect="dark"
            placement="top"
            :content="scope.row.skuId")
            div.cell.el-tooltip(style="padding: 0") {{scope.row.skuId}}
      el-table-column(label="名称")
        template(slot-scope="scope")
          div.act-td(@click="showMaterielDetail(scope.row)") {{scope.row.skuName}}
      el-table-column(show-overflow-tooltip, prop="brand", label="制造商")
        template(slot-scope="scope")
          span {{ scope.row.brand | compare-list(skuManSelect) }}
      el-table-column(show-overflow-tooltip, prop="spec", label="型号规格")
      el-table-column(show-overflow-tooltip, prop="unit", label="库存单位")
        template(slot-scope="scope")
          span {{ scope.row.unit | compare-list(skuUnitSelect) }}
      el-table-column(show-overflow-tooltip, prop="bomvertion", label="BOM版本")
      el-table-column(show-overflow-tooltip, prop="category", label="物料类别")
        template(slot-scope="scope")
          span {{ scope.row.category | compare-list(skuTypeSelect) }}
      el-table-column(show-overflow-tooltip, prop="grade", label="物料分级")
        template(slot-scope="scope")
          span {{ scope.row.grade | compare-list(skuLevelSelect) }}
      el-table-column(show-overflow-tooltip, prop="stores", label="仓库")
      el-table-column(show-overflow-tooltip, prop="quantity", label="数量")
        template(slot-scope="scope")
          div.act-td(@click="showQtPopup(scope.row)") {{scope.row.quantity}}
      el-table-column(label="操作")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="showInvDetailDiolog(scope.row)")
  //- 分页
  el-pagination.ov-pagination(
    background,
    layout="total, prev, pager, next, jumper",
    prev-text="上一页",
    next-text="下一页",
    @current-change="handleCurrentChange",
    :current-page="pageNum",
    :page-size="pageSize",
    :total="totalNum")
  //- 数量详情
  el-dialog.ov-dialog(
    :title="qtPopupTitle",
    :visible.sync="showQuantity",
    @close="closeQtPopup",
    width="80%")
    el-table.ov-pop-table(
      v-loading="qtLoad",
      :data="qtList",
      size="mini",
      stripe)
      el-table-column(show-overflow-tooltip, property="storehouseName", label="仓库")
      el-table-column(show-overflow-tooltip, property="storageSite", label="仓位")
      el-table-column(show-overflow-tooltip, property="batchNo", label="批号")
      el-table-column(show-overflow-tooltip, property="serialNo", label="序列号")
      el-table-column(show-overflow-tooltip, property="quantity", label="数量")
      el-table-column(show-overflow-tooltip, property="inventoryState", label="库存状态")
      el-table-column(show-overflow-tooltip, property="warningUp", label="预警上限")
      el-table-column(show-overflow-tooltip, property="warningDown", label="预警下限")
      el-table-column(show-overflow-tooltip, label="有效期至")
        template(slot-scope="scope")
          span {{scope.row.validityDate | day-format}}
      el-table-column(show-overflow-tooltip, property="validityDay", label="有效天数")
      el-table-column(show-overflow-tooltip, property="validityValue", label="有效期预警值")
    el-pagination.popup-page(
      layout="total, prev, pager, next, jumper",
      prev-text="上一页",
      next-text="下一页",
      @current-change="handleQtPage",
      :current-page="qtPageNum",
      :page-size="pageSize",
      :total="qtTotalNum")
    .dialog-footer(slot="footer")
      el-button(type="primary", plain, @click="showQuantity = false") 取消
      el-button(type="primary", @click="showQuantity = false") 确定
  //- 查看详情
  el-dialog.ov-dialog(
    :title="invDetailTitle",
    :visible.sync="showInvDetail",
    @close="closeInvDetail",
    width="80%")
    el-tabs(v-model="tabModel")
      el-tab-pane(label="出入库记录" name="record")
        //- 查询出入库记录
        el-form.ov-pop-search(:inline="true")
          el-form-item
            el-date-picker.date-width(
              v-model="popDateRange",
              type="daterange",
              unlink-panels,
              :clearable="false",
              start-placeholder="开始日期",
              end-placeholder="结束日期",
              value-format="timestamp",
              :default-time="['00:00:00', '23:59:59']")
          el-form-item(label="类型 :")
            el-select(v-model="popInvType", placeholder="请选择", style="width: 128px")
              el-option(label="全部", :value="null")
              el-option(
                v-for="item in allInvType",
                :key="item.value",
                :label="item.name",
                :value="item.value")
          el-form-item(label="仓库 :")
            el-select(v-model="popStorehouse", placeholder="请选择", style="width: 80px")
              el-option(label="全部", :value="null")
              el-option(
                v-for="item in allStorehouse",
                :key="item.value",
                :label="item.name",
                :value="item.value")
          el-form-item(label="仓管员 :")
            el-select(v-model="popCreator", placeholder="请选择", style="width: 80px")
              el-option(label="全部", :value="null")
              el-option(
                v-for="item in allKeeper",
                :key="item.value",
                :label="item.name",
                :value="item.value")
          el-form-item
            el-select(v-model="popKeyWordsType", placeholder="请选择", style="width: 80px")
              el-option(label="全部", :value="null")
              el-option(
                v-for="(item, index) in allKeyWordsType",
                :key="index",
                :label="item",
                :value="index")
          el-form-item
            el-input(v-model="popKeywords", @keyup.native.enter="searchRecord", placeholder="名称/品牌/型号/规格/编码/条码/", style="width: 220px")
              <i slot="suffix" class="el-input__icon el-icon-search" @click="searchRecord"></i>
        el-table.ov-pop-record-table(
          v-loading="recordLoading",
          :data="recordList",
          size="mini",
          stripe)
          el-table-column(show-overflow-tooltip, type="index", label="序号")
          el-table-column(show-overflow-tooltip, label="时间")
            template(slot-scope="scope")
              span {{scope.row.time | day-format}}
          el-table-column(show-overflow-tooltip, property="creator", label="仓管员")
          el-table-column(show-overflow-tooltip, property="skuType", label="单据类型")
          el-table-column(show-overflow-tooltip, property="skuId", label="单据编号")
          el-table-column(show-overflow-tooltip, property="storehouseName", label="仓库")
          el-table-column(show-overflow-tooltip, property="storageSite", label="仓位")
          el-table-column(show-overflow-tooltip, property="batchNo", label="批号")
          el-table-column(show-overflow-tooltip, property="serialNo", label="序列号")
          el-table-column(show-overflow-tooltip, property="modifyQuantity", label="变动数量")
          el-table-column(show-overflow-tooltip, property="balanceQuantity", label="结存数量")
          el-table-column(show-overflow-tooltip, property="inventoryUnit", label="库存单位")
          el-table-column(show-overflow-tooltip, property="inventoryState", label="库存状态")
          el-table-column(show-overflow-tooltip, property="remark", label="备注")
        el-pagination.popup-page(
          layout="total, prev, pager, next, jumper",
          prev-text="上一页",
          next-text="下一页",
          @current-change="handleRecordPage",
          :current-page="recordPageNum",
          :page-size="pageSize",
          :total="recordTotalNum")
        el-row(:gutter="20")
          el-col(:span="6", style="text-align: center;")
            p 初期数量：{{recordStartNum}}
          el-col(:span="6", style="text-align: center;")
            p 期末数量：{{recordEndNum}}
          el-col(:span="6", style="text-align: center;")
            p 本期累计入库数量：{{totalInboundNum}}
          el-col(:span="6", style="text-align: center;")
            p 本期累计出库数量：{{totalOutboundNum}}
      el-tab-pane(label="数量及预警" name="warning")
        el-table.ov-pop-table(
          v-loading="warningLoad",
          :data="warningList",
          size="mini",
          stripe)
          el-table-column(show-overflow-tooltip, property="storehouseName", label="仓库")
          el-table-column(show-overflow-tooltip, property="storageSite", label="仓位")
          el-table-column(show-overflow-tooltip, property="batchNo", label="批号")
          el-table-column(show-overflow-tooltip, property="serialNo", label="序列号")
          el-table-column(show-overflow-tooltip, property="quantity", label="数量")
          el-table-column(show-overflow-tooltip, property="inventoryState", label="库存状态")
          el-table-column(show-overflow-tooltip, property="warningUp", label="预警上限")
          el-table-column(show-overflow-tooltip, property="warningDown", label="预警下限")
          el-table-column(show-overflow-tooltip, label="有效期至")
            template(slot-scope="scope")
              span {{scope.row.validityDate | day-format}}
          el-table-column(show-overflow-tooltip, property="validityDay", label="有效天数")
          el-table-column(show-overflow-tooltip, property="warningDay", label="提前预警天数")
        el-pagination.popup-page(
          layout="total, prev, pager, next, jumper",
          prev-text="上一页",
          next-text="下一页",
          @current-change="handleDetailPage",
          :current-page="warnPageNum",
          :page-size="pageSize",
          :total="warnTotalNum")
    .dialog-footer(slot="footer")
      el-button(type="primary", plain, @click="exportInvDetail") 导出
      el-button(type="primary", @click="showInvDetail = false") 确定
  materiel-popup(
    :title="materielTitle",
    :visible="showMateriel",
    :view-status="true",
    :parent-data="materielData",
    @close="showMateriel = false")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import InventoryApi from '@/api/inventory';
import ManApi from '@/api/manage';
import materielPopup from '@/views/manage/materiel/materielPopup';

export default {
  name: 'invoverview',
  components: {
    materielPopup
  },
  data() {
    return {
      loadingOverview: true,
      inventoryViews: [],
      pageNum: 1,
      totalNum: 0,
      pageSize: 20,
      // 搜索条件
      keyWordsType: null,
      keywords: null,
      skuType: null,
      grade: null,
      viewStore: null,
      // 当前行
      currentRow: {},
      // 显示物料详情
      showMateriel: false,
      materielTitle: '查看物料',
      // 物料数据
      materielData: {
        status: '0',
        picture: [],
        qalerts: [],
        procurers: [],
        vendorSupplies: []
      },
      // 显示库存一览详情
      showInvDetail: false,
      invDetailTitle: '库存一览-查看详情',
      tabModel: 'record',
      // 出入库搜索
      popDateRange: [],
      popInvType: null,
      popStorehouse: null,
      popCreator: null,
      popKeyWordsType: null,
      popKeywords: '',
      recordStartNum: '',
      recordEndNum: '',
      totalInboundNum: '',
      totalOutboundNum: '',
      recordLoading: true,
      recordPageNum: 1,
      recordTotalNum: 0,
      recordList: null,
      // 数量及预警
      warningLoad: true,
      warnPageNum: 1,
      warnTotalNum: 0,
      warningList: null,
      // 数量弹框
      showQuantity: false,
      qtPopupTitle: '库存一览-数量及预警',
      qtLoad: true,
      qtPageNum: 1,
      qtTotalNum: 0,
      qtList: null,
      allKeyWordsType: ['名称', '品牌', '型号', '规格', '编码', '条码'],
      allInvType: []
    };
  },
  computed: {
    ...mapGetters({
      creator: 'employeeId',
      allStorehouse: 'storeSelect',
      allKeeper: 'keeperSelect',
      // 物料
      skuTypeSelect: 'skuTypeSelect',
      skuPropSelect: 'skuPropSelect',
      skuLevelSelect: 'skuLevelSelect',
      skuManSelect: 'skuManSelect',
      skuUnitSelect: 'unitSelect'
    })
  },
  created() {
    // 类型列表
    ComApi.getTypes({ orderType: 'overview' }).then((typeList) => {
      this.allInvType = typeList;
    });
  },
  mounted() {
    this.loadInventoryList();
  },
  methods: {
    indexMethod (i) {
      return ((this.pageNum - 1) * this.pageSize) + (i + 1);
    },
    filterParams() {
      const params = {
        creator: this.creator,
        keyWordsType: this.keyWordsType,
        keywords: this.keywords,
        category: this.skuType,
        grade: this.grade,
        store: this.viewStore,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      for (const key in params) {
        if (params[key] === null || params[key] === '' || params[key] === undefined) {
          delete params[key];
        }
      }
      return params;
    },
    // 取得所有库存
    loadInventoryList() {
      this.loadingOverview = true;
      const params = this.filterParams();
      // console.log(params);
      InventoryApi.getInventoryOverview(params).then((result) => {
        this.inventoryViews = result.records;
        this.totalNum = result.totalNum;
        this.loadingOverview = false;
      }).catch((error) => {
        this.loadingOverview = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 搜索
    search() {
      if (this.pageNum !== 1) {
        this.pageNum = 1;
      }
      this.loadInventoryList();
    },
    // 导出库存一览
    exportReport() {
      // console.log('库存一览导出exportReport');
    },
    // 页码改变
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.loadInventoryList();
    },
    // 查看物料详情
    showMaterielDetail(row) {
      ManApi.getMaterielDetail({ id: row.skuId }).then((result) => {
        this.materielData = result;
        this.showMateriel = true;
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 查看详情
    showInvDetailDiolog(row) {
      this.invDetailTitle = `库存一览-查看详情【${row.skuName}】`;
      this.currentRow = row;
      this.showInvDetail = true;
      this.loadInvRecordList();
      this.loadInvWarningList();
    },
    // 关闭详情
    closeInvDetail() {
      setTimeout(() => {
        this.recordPageNum = 1;
        this.recordTotalNum = 0;
        this.warnPageNum = 1;
        this.warnTotalNum = 0;
        this.invDetailTitle = '库存一览-查看详情';
        this.tabModel = 'record';
        // 出入库搜索
        this.popDateRange = [];
        this.popInvType = null;
        this.popStorehouse = null;
        this.popCreator = null;
        this.popKeyWordsType = null;
        this.popKeywords = '';
        this.recordStartNum = '';
        this.recordEndNum = '';
        this.totalInboundNum = '';
        this.totalOutboundNum = '';
      }, 10);
    },
    filterRecordParams() {
      const params = {
        skuId: this.currentRow.skuId,
        popStartDate: this.popDateRange[0] || '',
        popEndDate: this.popDateRange[1] || '',
        popInvType: this.popInvType,
        popStorehouse: this.popStorehouse,
        popCreator: this.popCreator,
        popKeyWordsType: this.popKeyWordsType,
        popKeywords: this.popKeywords,
        recordPageNum: this.recordPageNum
      };
      for (const key in params) {
        if (params[key] === null || params[key] === '' || params[key] === undefined) {
          delete params[key];
        }
      }
      return params;
    },
    // 搜索出入库记录
    searchRecord() {
      if (this.recordPageNum !== 1) {
        this.recordPageNum = 1;
      }
      this.loadInvRecordList();
    },
    // 出入库记录翻页
    handleRecordPage(pageNum) {
      this.recordPageNum = pageNum;
      this.loadInvRecordList();
    },
    // 获取出入库记录数据
    loadInvRecordList() {
      this.recordLoading = true;
      const params = this.filterRecordParams();
      InventoryApi.getRecordList(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.recordList = res.obj.records;
          this.recordTotalNum = res.obj.totalNum;
          this.recordStartNum = res.obj.recordStartNum;
          this.recordEndNum = res.obj.recordEndNum;
          this.totalInboundNum = res.obj.totalInboundNum;
          this.totalOutboundNum = res.obj.totalOutboundNum;
          this.recordLoading = false;
        } else {
          this.recordLoading = false;
          this.$message.error(res.comment || '获取数据失败');
        }
      }).catch((error) => {
        this.recordLoading = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 数量及预警分页
    handleDetailPage(pageNum) {
      this.warnPageNum = pageNum;
      this.loadInvWarningList();
    },
    // 获取数量及预警数据
    loadInvWarningList() {
      this.warningLoad = true;
      const params = {
        skuId: this.currentRow.skuId,
        pageNum: this.warnPageNum,
      };
      InventoryApi.getWarningList(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.warningList = res.obj.records;
          this.warnTotalNum = res.obj.totalNum;
          this.warningLoad = false;
        } else {
          this.warningLoad = false;
          this.$message.error(res.comment || '获取数据失败');
        }
      }).catch((error) => {
        this.warningLoad = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 导出库存详情
    exportInvDetail() {
      this.showInvDetail = false;
      // console.log('导出库存详情exportInvDetail');
    },
    // 查看数量
    showQtPopup(row) {
      this.qtPopupTitle = `库存一览-数量及预警【${row.skuName}】`;
      this.currentRow = row;
      this.showQuantity = true;
      this.loadQuantityList();
    },
    // 关闭数量弹窗
    closeQtPopup() {
      this.qtPageNum = 1;
      this.qtTotalNum = 0;
    },
    // 数量翻页
    handleQtPage(pageNum) {
      this.qtPageNum = pageNum;
      this.loadQuantityList();
    },
    // 获取数量列表
    loadQuantityList() {
      this.qtLoad = true;
      const params = {
        skuId: this.currentRow.skuId,
        pageNum: this.qtPageNum,
      };
      InventoryApi.getWarningList(params).then((res) => {
        if (res.status === 0 && res.obj) {
          this.qtList = res.obj.records;
          this.qtTotalNum = res.obj.totalNum;
          this.qtLoad = false;
        } else {
          this.qtLoad = false;
          this.$message.error(res.comment || '获取数据失败');
        }
      }).catch((error) => {
        this.qtLoad = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    }
  }
};
</script>

<style lang="sass">
@import "../../styles/utils"
$SEARCHHEIGHT: 56px
.cp-inv-overview
  .ov-search
    white-space: nowrap
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .ov-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: $SEARCHHEIGHT
    left: 16px
    right: 16px
    overflow: auto
    &::before
      display: none
    .act-td
      cursor: pointer
      color: #5D9BFB
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: 3px
    margin-right: 3px
    &:hover
      color: #5D9BFB
  .el-table
    th, td
      text-align: center
  .ov-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
  .ov-pop-table
    overflow: auto
    min-height: 360px
  .popup-page
    margin: 4px
    text-align: center
  .ov-dialog
    &::-webkit-scrollbar
      display: none
    .el-dialog
      margin-top: 5vh!important
      height: auto
      .el-dialog__footer
        text-align: center
        padding-top: 0
        .el-button
          width: 80px
          &:last-child
            margin-left: 40px
    .el-tabs__item:focus.is-active.is-focus:not(:active)
      box-shadow: none
    .el-tabs__nav-wrap::after
      background-color: white
  .el-dialog__body
    padding: 10px 20px
  .ov-pop-search
    .date-width
      width: 240px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
    .el-icon-search
      font-size: 16px
      font-weight: 500
      cursor: pointer
      &:hover
        color: #5D9BFB
</style>
